package gui;

import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JOptionPane;
import modelo.Motorista;
import modelo.dao.MotoristaJpaController;
import modelo.dao.exceptions.NonexistentEntityException;
import tableModel.MotoristaTableModel;
import util.ManangerEntity;
import tableModel.MotoristaRenderes;
import util.Mensagem;
import util.MaiusculaLimitadaAsg;


public class GUIGridMotorista extends javax.swing.JDialog {

    MotoristaJpaController dao = new MotoristaJpaController(ManangerEntity.getEntityManagerFactory());
    protected boolean dadosAlterados;
    Integer i;

    /**
     * Creates new form GUIGridMotorista
     */
    public GUIGridMotorista(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        tfLocalizar.grabFocus();
        carregarMotoristas();
        // tbMotoristas.setRowSelectionInterval(0, 0);
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbMotoristas = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        lbNome = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        tfLocalizar = new javax.swing.JTextField();
        tfLocalizar.setDocument(new MaiusculaLimitadaAsg(50, true));
        jPanel4 = new javax.swing.JPanel();
        btOk = new javax.swing.JButton();
        btIncluir = new javax.swing.JButton();
        btExcluir = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();
        btSair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Motoristas");
        setPreferredSize(new java.awt.Dimension(800, 500));

        jPanel1.setLayout(new java.awt.BorderLayout());

        tbMotoristas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tbMotoristas.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbMotoristasKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(tbMotoristas);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel5.setLayout(new java.awt.GridLayout(1, 0));

        lbNome.setText("Localizar:");
        jPanel5.add(lbNome);

        jPanel3.add(jPanel5, java.awt.BorderLayout.WEST);

        jPanel6.setLayout(new javax.swing.BoxLayout(jPanel6, javax.swing.BoxLayout.LINE_AXIS));

        tfLocalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfLocalizarActionPerformed(evt);
            }
        });
        tfLocalizar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfLocalizarKeyPressed(evt);
            }
        });
        jPanel6.add(tfLocalizar);

        jPanel3.add(jPanel6, java.awt.BorderLayout.CENTER);

        jPanel2.add(jPanel3, java.awt.BorderLayout.CENTER);

        jPanel4.setLayout(new java.awt.GridLayout(1, 0));

        btOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icones24x24/Apply.png"))); // NOI18N
        btOk.setText("OK");
        btOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btOkActionPerformed(evt);
            }
        });
        jPanel4.add(btOk);

        btIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icones24x24/Add.png"))); // NOI18N
        btIncluir.setText("Incluir");
        btIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIncluirActionPerformed(evt);
            }
        });
        jPanel4.add(btIncluir);

        btExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icones24x24/Delete.png"))); // NOI18N
        btExcluir.setText("Excluir");
        btExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluirActionPerformed(evt);
            }
        });
        jPanel4.add(btExcluir);

        btAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icones24x24/Update.png"))); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });
        jPanel4.add(btAlterar);

        btSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icones24x24/Exit.png"))); // NOI18N
        btSair.setText("Sair");
        btSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSairActionPerformed(evt);
            }
        });
        jPanel4.add(btSair);

        jPanel2.add(jPanel4, java.awt.BorderLayout.EAST);

        getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btOkActionPerformed
        if (tfLocalizar.getText().equals("")) {
            carregarMotoristas();
        } else {
            List<Motorista> list = dao.getMotoristasByNome(tfLocalizar.getText());
            tbMotoristas.setModel(new MotoristaTableModel(list));
            MotoristaRenderes.defineRenderers(tbMotoristas);
        }
    }//GEN-LAST:event_btOkActionPerformed

    private void btIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btIncluirActionPerformed
        GUICadMotorista gui = new GUICadMotorista(true, null);
        if (gui.encerrado()) {
            carregarMotoristas();
        }
    }//GEN-LAST:event_btIncluirActionPerformed

    private void btExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluirActionPerformed
        if (tbMotoristas.getSelectedRowCount() == 0) {
            Mensagem.exibirMensagem("Selecione um registro primeiro", "Atenção", true);
        } else {
            if (JOptionPane.showConfirmDialog(null, "Deseja Excluir o Registro?",
                    "Confirmar", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                try {
                    dao.destroy((Integer) tbMotoristas.getValueAt(tbMotoristas.getSelectedRow(), 0));
                    carregarMotoristas();
                } catch (NonexistentEntityException ex) {
                    util.Mensagem.exibirMensagem(ex.getMessage(), "Erro daoMotorista, NonexistentEntityException", true);
                }
            }
        }
    }//GEN-LAST:event_btExcluirActionPerformed

    private void tfLocalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfLocalizarActionPerformed
        btOkActionPerformed(evt);
    }//GEN-LAST:event_tfLocalizarActionPerformed

    private void tbMotoristasKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbMotoristasKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            if (tbMotoristas.getSelectedRowCount() == 0) {
                Mensagem.exibirMensagem("Selecione um registro primeiro", "Atenção", true);
            } else {
                Integer ItemSel = (Integer) tbMotoristas.getValueAt(tbMotoristas.getSelectedRow(), 0);
                setMotSelecionado(ItemSel);
                dadosAlterados = true;
                setVisible(false);
            }
        }
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            this.dispose();
        }
    }//GEN-LAST:event_tbMotoristasKeyPressed

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        if (tbMotoristas.getSelectedRowCount() == 0) {
            Mensagem.exibirMensagem("Selecione um registro primeiro", "Atenção", true);
        } else {
            int motoristaId = (Integer) tbMotoristas.getValueAt(tbMotoristas.getSelectedRow(), 0);
            Motorista motorista = dao.findMotorista(motoristaId);
            GUICadMotorista gui = new GUICadMotorista(false, motorista);
            if (gui.encerrado()) {
                carregarMotoristas();
            }
        }
    }//GEN-LAST:event_btAlterarActionPerformed

    private void tfLocalizarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfLocalizarKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_tfLocalizarKeyPressed

    private void btSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairActionPerformed
        dispose();
    }//GEN-LAST:event_btSairActionPerformed

    private void carregarMotoristas() {
        List<Motorista> list = dao.findMotoristaEntities();
        tbMotoristas.setModel(new MotoristaTableModel(list));
        MotoristaRenderes.defineRenderers(tbMotoristas);
    }

    public boolean alterarDados() {
        dadosAlterados = false;  //Marcamos que o dados 
        setModal(true);         //A dialog tem que ser modal. Só pode retornar do setVisible após ficar invisível.
        setVisible(true);       //Mostramos a dialog e esperamos o usuário escolher alguma coisa.
        return dadosAlterados;   //Retornamos true, se ele pressionou ok.
    }

    public Integer getMotSelecionado() {
        return i;
    }

    public void setMotSelecionado(Integer i) {
        this.i = i;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btExcluir;
    private javax.swing.JButton btIncluir;
    private javax.swing.JButton btOk;
    private javax.swing.JButton btSair;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbNome;
    private javax.swing.JTable tbMotoristas;
    private javax.swing.JTextField tfLocalizar;
    // End of variables declaration//GEN-END:variables
}
